<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'wms:pack:wmsPackH:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="65%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #wmsPackCList>
        <BasicTable @register="registerWmsPackCTable" @row-click="handleWmsPackCRowClick" />
        <a-button class="mt-2" @click="handleWmsPackCAdd" v-auth="'wms:pack:wmsPackH:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsWmsPackWmsPackHForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { WmsPackH, wmsPackHSave, wmsPackHForm } from '/@/api/bas/wms/pack/wmsPackH';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wms.pack.wmsPackH');
  const { showMessage } = useMessage();
  const record = ref<WmsPackH>({} as WmsPackH);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增装箱') : t('编辑装箱'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('装箱编号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('条码内容'),
      field: 'text',
      component: 'Input',
      componentProps: {
        maxlength: 2000,
      },
      required: true,
    },
    {
      label: t('装箱业务类型'),
      field: 'cbustype',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('装箱时间'),
      field: 'packDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      required: true,
    },
    {
      label: t('装箱人'),
      field: 'packBy',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('装箱子表'),
      field: 'wmsPackCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'wmsPackCList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerWmsPackCTable, wmsPackCTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleWmsPackCDelete.bind(this, record),
          },
          auth: 'wms:pack:wmsPackH:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setWmsPackCTableData(_res: Recordable) {
    wmsPackCTable.setColumns([
      {
        title: t('存货编码'),
        dataIndex: 'invCode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('批次'),
        dataIndex: 'cbatch',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: true,
      },
      {
        title: t('累计操作数'),
        dataIndex: 'sumQty',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('业务ID'),
        dataIndex: 'cbusid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
    ]);
    wmsPackCTable.setTableData(record.value.wmsPackCList || []);
  }

  function handleWmsPackCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleWmsPackCAdd() {
    wmsPackCTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleWmsPackCDelete(record: Recordable) {
    wmsPackCTable.deleteTableDataRecord(record);
  }

  async function getWmsPackCList() {
    let wmsPackCListValid = true;
    let wmsPackCList: Recordable[] = [];
    for (const record of wmsPackCTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        wmsPackCListValid = false;
      }
      wmsPackCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of wmsPackCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      wmsPackCList.push({
        ...record,
        status: '1',
      });
    }
    if (!wmsPackCListValid) {
      throw { errorFields: [{ name: ['wmsPackCList'] }] };
    }
    return wmsPackCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await wmsPackHForm(data);
    record.value = (res.wmsPackH || {}) as WmsPackH;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setWmsPackCTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.wmsPackCList = await getWmsPackCList();
      // console.log('submit', params, data, record);
      const res = await wmsPackHSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
